from flask import render_template, redirect, g, request, jsonify, current_app, abort

from info import constants, db
from info.models import Category, News, User
from info.utils.common import user_login_data
from info.utils.image_storege import storage
from info.utils.response_code import RET
from . import profile_blu


@profile_blu.route('/other_news_list')
@user_login_data
def other_news_list():
    other_id = request.args.get('user_id')
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="查询错误")
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    if not other:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    current_page = 1
    total_page = 1
    user_list = []
    user_dict_li = []
    try:
        paginate = other.news_list.paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        current_page = paginate.page
        user_list = paginate.items
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    print(user_list)
    for user in user_list:
        user_dict_li.append(user.to_dict())

    data = {
        'current_page': current_page,
        'total_page': total_page,
        'news_list': user_dict_li
    }
    return jsonify(errno=RET.OK, errmsg="成功", data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    other_id = request.args.get('user_id')
    if not other_id:
        abort(404)
    other = None
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)
    if not other:
        abort(404)
    is_followed = False
    if g.user and other:
        if g.user in other.followers:
            is_followed = True
    data = {
        'other_info': other.to_dict(),
        'is_followed': is_followed}

    return render_template('news/other.html', data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    user = g.user
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    current_page = 1
    total_page = 1
    user_list = []
    user_dict_li = []
    try:
        paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
        current_page = paginate.page
        total_page = paginate.pages
        user_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    for user in user_list:
        user_dict_li.append(user.to_dict())
    data = {
        'current_page': current_page,
        'total_page': total_page,
        'users': user_dict_li
    }
    return render_template('news/user_follow.html', data=data)


@profile_blu.route('/collection')
@user_login_data
def use_collection():
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    data = {
        'current_page': current_page,
        'collections': news_dict_li,
        'total_page': total_page
    }

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    if request.method == "GET":
        return render_template('news/user_pass_info.html', data={'user': g.user.to_dict()})
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    user = g.user
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")
    user.password = new_password
    return jsonify(errno=RET.OK, errmsg="成功")


@profile_blu.route('/base_info', methods=["GET", "POST"])
@user_login_data
def base_info():
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={'user': g.user.to_dict()})
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="查询错误")
    if gender not in ('WOMAN', 'MAN'):
        return jsonify(errno=RET.PARAMERR, errmsg="性别错误")
    user = g.user
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    return jsonify(errno=RET.OK, errmsg="成功")


@profile_blu.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={'user': user.to_dict()})
    try:
        avatar = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        key = storage(avatar)
    except Exception as e:
        print(e)
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="上传失败")

    # 报错头像
    user.avatar_url = key
    return jsonify(errno=RET.OK, errmsg="OK", data={'avatar_url': constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route('/news_release', methods=["GET", "POST"])
@user_login_data
def news_release():
    user = g.user
    if request.method == "GET":
        categories = Category.query.all()
        category_dict = []
        for category in categories:
            category_dict.append(category.to_dict())
        category_dict.pop(0)
        return render_template('news/user_news_release.html', data={'categories': category_dict})
    title = request.form.get('title')
    digest = request.form.get('digest')
    source = '个人发布'
    content = request.form.get('content')
    index_image = request.files.get('index_image')
    category_id = request.form.get('category_id')
    if not all([title, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="数据错误")
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        index_image_data = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取错误")
    try:
        key = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="上传失败")
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = user.id
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    return jsonify(errno=RET.OK, errmsg="成功")


#
@profile_blu.route('/news_list')
@user_login_data
def user_news_list():
    user = g.user
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    current_page = 1
    total_page = 1
    news_list_li = []
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list_li = paginate.items
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    news_dict = []
    for news in news_list_li:
        news_dict.append(news.to_review_dict())
    data = {
        'current_page': current_page,
        'news_list': news_dict,
        'total_page': total_page
    }
    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/info')
@user_login_data
def user_collection():
    user = g.user
    if not user:
        # 代表没有登录，重定向到首页
        return redirect("/")
    data = {"user": user.to_dict()}
    return render_template('news/user.html', data=data)
